#include "pebble_os.h"
#include "pebble_app.h"
#include "pebble_fonts.h"
#include "menu_{{menu_name|lower}}.h"
#include "command.h"

#define GET_BIT(var,pos) ((var >> pos)&1)

static Window window;

static void doSomething(int index, void* context);

static SimpleMenuItem menu_items[] = {
    {%- for key in items %}
    {
        .title = "{{key}}",
        .callback = doSomething,
    },
    {%- endfor %}
};

static SimpleMenuSection section = {
    .items = menu_items,
    .num_items = ARRAY_LENGTH(menu_items),
};

static SimpleMenuLayer menu_layer;

static int get_selected(){
    {% if bit_index is defined -%}
    switch(GET_BIT(data[{{ index_in_data }}],{{ bit_index }})){
    {%- else -%}
    switch(data[{{ index_in_data }}]){
    {%- endif -%}
    {%- for key, value in items.iteritems(): %}
        case {{ value }}: return {{ loop.index0 }};  break;
    {%- endfor %}
    }
    return 0;
}

static void window_load(Window* window) {
    simple_menu_layer_init(&menu_layer, GRect(0, 0, 144, 160), window, &section, 1, NULL);
    layer_add_child(window_get_root_layer(window), simple_menu_layer_get_layer(&menu_layer));
}

static void window_appear(Window* window) {
     simple_menu_layer_set_selected_index(&menu_layer,get_selected(), true);
}

void show_menu_{{menu_name|lower}}(int firstItem) {
    window_init(&window, "{{menu_name|capitalize}}");
    window_set_window_handlers(&window, (WindowHandlers){
        .load = window_load,
        .appear = window_appear,
    });
    window_stack_push(&window, true);
}

static void doSomething(int index, void* context) {
    switch(index){
    {%- for key, value in items.iteritems(): %}
        case {{ loop.index0 }}: send_camera_cmd("{{command_name}}",{{value}});  break;
    {%- endfor %}
    }
}

const char* get_{{ menu_name }}_str(){
    {% if bit_index is defined -%}
    switch(GET_BIT(data[{{ index_in_data }}],{{ bit_index }})){
    {%- else -%}
    switch(data[{{ index_in_data }}]){
    {%- endif -%}
    {%- for key, value in items.iteritems(): %}
        case {{ value }}: return "{{ key }}";  break;
    {%- endfor %}
    }
    return "";
}
